<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <style type="text/css">
        body,
        html {
            width: 100%;
            height: 100%;
            margin: 0;
            font-family: "微软雅黑";
        }

        #mapContainer {
            width: 100%;
            height: 100%;
        }

        body,
        div,
        dl,
        dt,
        dd,
        ul,
        ol,
        li,
        h1,
        h2,
        h3,
        h4,
        h5,
        h6,
        pre,
        form,
        fieldset,
        input,
        textarea,
        p,
        blockquote,
        th,
        td {
            padding: 0;
            margin: 0;
        }

        .lv0,
        .lv1,
        .lv2,
        .lv3,
        .lv4,
        .remark {
            font: 14px/22px Helvetica, 'Hiragino Sans GB', Arial, 'Microsoft YaHei', sans-serif;
            color: #fff;
            text-align: center;
            background-repeat: no-repeat;
        }

        .lv0 {
            background-image: url(map.png?v=1562057669302);
            padding: 16px 0 0;
            width: 76px;
            height: 60px;
            margin: -38px 0 0 -38px;
            cursor: pointer;
        }

        .lv0>i {
            display: block;
            font-size: 16px;
        }

        .lv4 {
            font-size: 14px;
            background-color: #4081D6;
            padding: 3px 20px;
            opacity: 0.9;
            cursor: pointer;
            -moz-border-radius: 100px;
            -webkit-border-radius: 100px;
            border-radius: 100px;
        }
    </style>
    <script type="text/javascript"
        src="https://api.map.baidu.com/api?v=2.0&ak=自行修改"></script>
    <script type="text/javascript"
        src="https://api.map.baidu.com/library/TextIconOverlay/1.2/src/TextIconOverlay_min.js">
        </script>
    <script type="text/javascript"
        src="https://api.map.baidu.com/library/MarkerClusterer/1.2/src/MarkerClusterer_min.js">
        </script>
    <title>点聚合</title>
</head>

<body>
    <div id="mapContainer"></div>
    <div id="demo" style="position: fixed;top: 10px;left: 20px;background-color: #666;padding: 6px;color: #fff;"></div>
</body>
<script src="strokes.js"></script>
<script src="search.js"></script>
<script type="text/javascript">
    var _ = this;
    _.options = {
        //地图承载容器的选择器
        ele: "Map",
        //持久化状态的对象
        status: {},
        //由于百度地图渲染存在延迟，所以目前每次重新打点或者描边时候，都是需要在百度
        //地图渲染完成后操作，这边设置了一个渲染的延迟时间，默认为300毫秒
        time: 300,
        //默认设置满屏下拖动多少范围内不需要重新请求渲染地图
        bounds: 0.3,
        styles: {
            //地图画圈样式相关配置
            circle: {
                distance: 1000, //默认为一公里范围内的圈
                strokeColor: '#ffa200',
                strokeWeight: 2,
                strokeOpacity: 1,
                fillColor: '#ffa200',
                fillOpacity: 0.05,
                enableClicking: false
            },
            //地铁直线的样式
            line: {
                strokeColor: '#ffa200',
                strokeWeight: 6,
                strokeOpacity: 0.85
            },
            //描边的样式配置
            stroke: {
                strokeWeight: 4,
                strokeColor: '#ffa200',
                fillColor: '#333',
                fillOpacity: 0.05,
                strokeOpacity: 0.85,
                enableClicking: false
            }
        }
    };
    //获取可视范围信息
    function bounds(i) {
        var _ = this;

        i = i || 0;
        var bs = _.map.getBounds(); //获取可视区域
        var sw = bs.getSouthWest(); //可视区域左下角(西南角)
        var ne = bs.getNorthEast(); //可视区域右上角(东北角)

        return {
            'minLon': sw.lng - (ne.lng - sw.lng) * i,
            'maxLon': ne.lng + (ne.lng - sw.lng) * i,
            'minLat': sw.lat - (ne.lat - sw.lat) * i,
            'maxLat': ne.lat + (ne.lat - sw.lat) * i
        };
    };
    //标签事件绑定
    function addListenerToLabel(label) {
        label.addEventListener('mouseover', function () {
            if (_.zoomlevel >= 14) {
                // alert("");
            } else {
                let params = JSON.parse(this.V.querySelector(".WKBigDataBtn").getAttribute("data-params"));
                console.log(params);
                const stroke = strokes[params.key];
                if (!stroke) return;
                var d = stroke.data;
                var p = [];
                for (var i = d.length - 1; i >= 0; i--) {
                    p.push(new BMap.Point(d[i].lon, d[i].lat));
                };
                if (p.length > 0) {
                    let hover = new BMap.Polygon(p, _.options.styles.stroke);
                    _.map.addOverlay(hover);

                    //持久化当前的描边数据，避免同一区块重复请求数据描边
                    _.hover.push(hover);
                }
            }
        });
        label.addEventListener('mouseout', function () {
            if (_.zoomlevel >= 14) {
                // alert("");
            } else {
                for (var i = _.hover.length - 1; i >= 0; i--) {
                    _.map.removeOverlay(_.hover[i]);
                }
            }
        });
        label.addEventListener('click', function () {
            this.V.classList.add('over');
            if (_.zoomlevel >= 14) {
                alert("");
            } else {
                _.map.centerAndZoom(this.getPosition(), 14);
            }
        });
    }
    // 数据渲染
    function render() {
        let bs = bounds();
        let lv = _.zoomlevel;
        document.getElementById("demo").innerHTML = `Zoom:${lv}<br />` + Object.keys(bs).map(k => `${k}:${bs[k]}`).join("<br />");
        clear();
        /* 
        // 模拟 获取数据....
        */
        bs.lv = lv >= 14 ? 1 : 0;
        let data = search(bs);
        // if (lv >= 14) {
            renderLabel(data);
        // } else {
        //     renderLabel(data);
        // }
    }
    // 标签渲染
    function renderLabel(data) {
        for (let labelData of data) {
            let labelContent;
            if (_.zoomlevel >= 14) {
                labelContent = '<div class="WKBigDataBtn lv4" data-params="#BIGDATA#" ><p class="name">' + labelData.value + '</p><p>' + labelData.avgPrice + ' 元/㎡</p></div>'
            } else {
                labelContent = `<p class="WKBigDataBtn lv0" data-params='${JSON.stringify(labelData)}' >${labelData.value}<i>${labelData.count}</i></p>`;
            }
            let tmpLabel = new BMap.Label(labelContent, { position: new BMap.Point(labelData.lon, labelData.lat) });
            tmpLabel.key = labelData.key;
            tmpLabel.name = labelData.value;
            // tmpLabel.count = labelData.count;

            tmpLabel.setStyle({ border: 0, background: '', padding: 0 });
            tmpLabel.setZIndex(2);
            _.map.addOverlay(tmpLabel);
            addListenerToLabel(tmpLabel);
        }
    }
    function clear() {
        var p = _.map.getOverlays();
        for (var i = p.length - 1; i >= 0; i--) {
            _.map.removeOverlay(p[i]);
        }
    }
    _.map = new BMap.Map("mapContainer", { enableMapClick: false, minZoom: 8, maxZoom: 18 });
    _.map.centerAndZoom(new BMap.Point(121.113977, 31.14338), 11);
    _.hover = [];
    // _.map.addEventListener('load', function () { //地图加载完成
    _.map.enableScrollWheelZoom(); //启用滚轮放大缩小
    // _.map.setMinZoom(9); //设置地图允许的最小级别。取值不得小于地图类型所允许的最小级别
    _.map.disableDoubleClickZoom(); //禁止双击放大
    _.map.disableInertialDragging(); //禁用地图惯性拖拽
    //添加比例尺控件
    _.map.addControl(new BMap.ScaleControl({
        anchor: BMAP_ANCHOR_BOTTOM_LEFT
    }));
    //添加默认缩放平移控件
    _.map.addControl(new BMap.NavigationControl({
        anchor: BMAP_ANCHOR_BOTTOM_RIGHT
    }));
    _.map.addEventListener('dragend', function () {
        render();
    })
    _.map.addEventListener('zoomstart', function () {
        // _.loadingMap = true
    });
    _.map.addEventListener('zoomend', function () {
        _.zoomlevel = _.map.getZoom();
        render();
    })
    render();
    // });
</script>

</html>